package com.heima.comment.service.impl;
import java.math.BigDecimal;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.user.UserFeign;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentLikeVo;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private UserFeign userFeign;

//    int index=0;
    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        Integer size = dto.getSize();
        if (size == null || size == 0) {
            size = 10;
        }
        Date minDate = dto.getMinDate();
        if (minDate == null) {
            minDate = new Date();
        }
        //2. 条件查询评论回复信息
        //   条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lte(minDate));
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
//        query.with(PageRequest.of(index,size));
        query.limit(size);
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
//        if(apCommentRepayList.size()<=size&&apCommentRepayList.size()!=0&&apCommentRepayList!=null){
//            index++;
//        }
        if(apCommentRepayList.size()==0||apCommentRepayList==null){
            CustException.cust(AppHttpCodeEnum.NULL_COMMENT);
        }
        //3. 检查是否登录
        //   3.1 如果未登录直接 返回评论回复列表
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if(userId==0){
            return ResponseResult.okResult(apCommentRepayList);
        }else {
            List<ApCommentRepayVO> apCommentRepayVOList = getApCommentRepayVOS(apCommentRepayList, userId);
            return ResponseResult.okResult(apCommentRepayVOList);
        }
    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) throws Exception {
        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if (userId == 0) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ResponseResult<ApUser> userById = userFeign.findUserById(userId);
        ApUser apUser = userById.getData();
        String content = dto.getContent();
        if (content.length() > 140) {
            CustException.cust(AppHttpCodeEnum.EXCEED_BOUND);
        }
        //   回复内容安全校验
        //        简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        ScanResult scanResult = greenScan.greenTextScan(content);
        System.err.println("scanResult = " + scanResult);
        //过滤敏感词之后的评论
        String filteredContent = scanResult.getFilteredContent();
        System.err.println("filteredContent = " + filteredContent);
        if(StringUtils.isBlank(filteredContent)&&!scanResult.getSuggestion().equals("pass")){
            CustException.cust(AppHttpCodeEnum.COMMENT_FAILURE);
        }
        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if(apComment==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该评论已删除");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(userId);
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        if(filteredContent==null) {
            apCommentRepay.setContent(content);
        }else {
            apCommentRepay.setContent(filteredContent);
        }
        apCommentRepay.setLikes(0);
        apCommentRepay.setLongitude(new BigDecimal("0"));
        apCommentRepay.setLatitude(new BigDecimal("0"));
        apCommentRepay.setAddress("");
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        Update update = new Update();
        Integer reply = apComment.getReply()+1;
        update.set("reply",reply);
        mongoTemplate.updateFirst(query,update,ApComment.class);
        return ResponseResult.okResult("回复成功");
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //       回复id不能为空   operation 必须 0 或 1
        Short operation = dto.getOperation();
        if (operation != 0 && operation != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        Integer userId = user.getId();
        if (userId == 0) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //       校验回复信息是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "该评论已删除");
        }

        if (operation == 0) {
            saveRepayLikeComment(dto, userId, apCommentRepay);
            ApCommentRepay apCommentRepay1 = mongoTemplate.findOne(query, ApCommentRepay.class);
            Integer likes = apCommentRepay1.getLikes();
            ApCommentLikeVo apCommentLikeVo = new ApCommentLikeVo();
            apCommentLikeVo.setLikes((long)likes);
            return ResponseResult.okResult(apCommentLikeVo);
        } else if (operation == 1) {
            deleteRepayLikeComment(dto, userId, apCommentRepay);
            ApCommentRepay apCommentRepay1 = mongoTemplate.findOne(query, ApCommentRepay.class);
            Integer likes = apCommentRepay1.getLikes();
            ApCommentLikeVo apCommentLikeVo = new ApCommentLikeVo();
            apCommentLikeVo.setLikes((long)likes);
            return ResponseResult.okResult(apCommentRepay1);
        }
        return null;
    }



    /**
     * 用户登录获取点赞过的评论集合ApCommentRepayVOS字段operation为0
     * @param apCommentRepayList
     * @param userId
     * @return
     */
    private List<ApCommentRepayVO> getApCommentRepayVOS(List<ApCommentRepay> apCommentRepayList, Integer userId) {
        //   3.2 如果登录，需要判断哪些回复点过赞
        //   思路:
        //        基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        //遍历 当前回复列表，将每一个回复信息 封装成 vo
        List<ApCommentRepayVO> apCommentRepayVOList = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepayList) {
            Query query1 = Query.query(Criteria.where("commentRepayId").is(apCommentRepay.getId())
                    .and("authorId").is(userId));
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
            if(apCommentRepayLike!=null) {
                //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
                apCommentRepayVO.setOperation((short)0);
                apCommentRepayVOList.add(apCommentRepayVO);
                continue;
            }
            apCommentRepayVOList.add(apCommentRepayVO);
        }
        return apCommentRepayVOList;
    }

    /**
     * 删除点赞回复信息
     *
     * @param dto
     * @param userId
     * @param apCommentRepay
     */
    private void deleteRepayLikeComment(CommentRepayLikeDTO dto, Integer userId, ApCommentRepay apCommentRepay) {
        Query query = Query.query(Criteria.where("authorId").is(userId)
                .and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike != null) {
            //删除点赞信息
            mongoTemplate.remove(apCommentRepayLike);
            //点赞数量-1,且不能为负数
            Query query1 = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
            Integer likes = apCommentRepay.getLikes() - 1;
            if (likes >= 0) {
                Update update = new Update();
                update.set("likes", likes);
                mongoTemplate.updateFirst(query1, update, ApCommentRepay.class);
            } else {
                //提示未点赞
                CustException.cust(AppHttpCodeEnum.NEED_UnLike, "未给此条评论点赞");
            }
        }
    }

    /**
     * 回复信息点赞操作
     *
     * @param dto
     * @param userId
     * @param apCommentRepay
     */
    private void saveRepayLikeComment(CommentRepayLikeDTO dto, Integer userId, ApCommentRepay apCommentRepay) {
        //1. 如果是点赞  判断是否点过赞
        Query query = Query.query(Criteria.where("authorId").is(userId)
                .and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (apCommentRepayLike == null) {
            //保存点赞
            ApCommentRepayLike apCommentRepayLike1 = new ApCommentRepayLike();
            apCommentRepayLike1.setAuthorId(userId);
            apCommentRepayLike1.setCommentRepayId(dto.getCommentRepayId());
            apCommentRepayLike1.setOperation((short) 0);
            //      未点过赞， 保存点赞信息
            mongoTemplate.save(apCommentRepayLike1);
            //并修改评论信息的点赞数量( + 1)
            Query query1 = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
            Integer likes = apCommentRepay.getLikes() + 1;
            Update update = new Update();
            update.set("likes", likes);
            mongoTemplate.updateFirst(query1, update, ApCommentRepay.class);
        } else {
            //提示请勿重复点赞
            CustException.cust(AppHttpCodeEnum.NEED_UnLike, "请勿重复点赞");
        }
    }
}
